/*
 * @Description: 权限生成
 * @Author: huacong
 * @Date: 2020-11-02 16:53:20
 * @LastEditTime: 2020-11-04 14:21:38
 * @LastEditors: huacong
 */

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i])
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}

function filterAsyncRouter(routerMap, permissionList) {
  const accessedRouters = routerMap.filter(route => {
    if (hasPermission(permissionList, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, permissionList)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const GenerateRoutes = (routs, data) => {
  return new Promise(resolve => {
    const accessedRouters = filterAsyncRouter(routs, data)
    resolve(accessedRouters)
  })
}

export default GenerateRoutes
